from PIL import ImageFont,ImageDraw,Image
import random
import io
import string
import re

tel = r"^0?(13[0-9]|15[012356789]|18[012346789]|14[57]|17[5-8]|170[059]|14[57]|166|19[89])[0-9]{8}$"
mail = r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?"
def check_re(pattern,data):
    rs = re.match(pattern,data)
    if rs:
        return True
    return False
def checkup_signup(uname,upasswd1,upasswd2,utel,uemail):
    result=()
    if len(uname) < 6 or len(uname) > 40:
       result = (False,"用户名少于6位或者太长")
    elif len(upasswd1)<6 or len(upasswd1)>40:
        result = (False,"请输入6到40位的密码")
    elif upasswd1 != upasswd2:
        result = (False,"密码前后不一致")
    elif check_re(utel):
        result = (False,"电话号码错误")
    elif check_re(uemail):
        result = (False,"邮箱错误")
    else:
        result = (True,"表单正确")
    return result

def gen_captchalib():
    # 定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100),random.randrange(20, 100), 255)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB',(width, height),bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = string.ascii_letters + string.digits
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象
    font = ImageFont.truetype("C:\Windows\Fonts\simsunb.ttf",20)
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 内存文件操作
    image = io.BytesIO()
    # 将图片保存在内存中，文件类型为png
    im.save(image, 'png')
    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    return (image.getbuffer(),rand_str)